<template>
    <el-upload class="upload"
               ref="upload"
               :action="sUrl"
               :show-file-list="false"
               :headers="oHeaders"
               :accept="sAccept"
               :multiple="multiple"
               :before-upload="fBeforeUpload"
               :on-success="fUploadSuccess"
               :on-error="fUploadError">
        <slot></slot>
    </el-upload>
</template>
<script>
    import { URLS_COM } from '@/urls'
    export default {
        props: {
            type: {// 上传类型 image-图片 默认不限制
                type: String,
                default: ''
            },
            multiple: {// 是否可以多选
                type: Boolean,
                default: true
            },
            uploadSuccess: { //上传成功的回调
                type: Function
            },
            uploadError: { //上传失败的回调
                type: Function
            },
            maxSize: {// 上传图片最大大小，单位M
                type: Number,
                default: 5
            }
        },
        data() {
            return {
                sUrl: URLS_COM.d_upload,
                oHeaders: {},
            }
        },
        computed: {
            sAccept() {
                switch (this.type) {
                    case 'image':
                        return '.jpg,.jpeg,.gif,.png,.bmp'
                    default:
                        return this.type
                }
            }
        },
        mounted() {
            let oTemp = {};
            oTemp[this.G_API.sTokenField] = this.G_API.fGetToken();
            this.oHeaders = oTemp;
        },
        methods: {
            fBeforeUpload(oFile) {
                if (oFile.size / 1024 / 1024 > this.maxSize) {
                    this.$message.error('上传文件大小不能超过 ' + this.maxSize + 'M')
                    return false;
                }
                return true
            },
            fUploadSuccess({ success, msg, data }) {
                if (success !== true) {
                    this.$message.error(msg || '上传失败');
                    return;
                }
                this.$emit('upload-success', data);// 每次上传成功一个文件就会跑回调
            },
            fUploadError(err) {
                this.$message.error(err);
            }
        }
    }
</script>
<style lang="less" scoped>
    ::v-deep.upload .el-upload {
        width: 100%;
        height: 100%;
        cursor: pointer;
        overflow: hidden;
    }
</style>